document.addEventListener('DOMContentLoaded', function() {
  // 初始化地图
  const map = new qq.maps.Map(document.getElementById('map'), {
    center: new qq.maps.LatLng(39.9042, 116.4074), // 默认北京中心
    zoom: 13
  });

  // 获取用户当前位置
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      position => {
        const userLocation = new qq.maps.LatLng(
          position.coords.latitude,
          position.coords.longitude
        );
        map.setCenter(userLocation);
        addUserMarker(userLocation);
        searchNearbyShops(position.coords.latitude, position.coords.longitude);
      },
      error => {
        console.error('获取位置失败:', error);
        // 使用默认位置
        searchNearbyShops(39.9042, 116.4074);
      }
    );
  } else {
    console.error('浏览器不支持地理位置API');
    searchNearbyShops(39.9042, 116.4074);
  }

  // 搜索按钮事件
  document.getElementById('search-btn').addEventListener('click', function() {
    const center = map.getCenter();
    const keyword = document.getElementById('search-input').value || '店铺';
    const category = document.getElementById('category-select').value;
    const radius = parseInt(document.getElementById('radius-range').value);
    
    searchNearbyShops(center.getLat(), center.getLng(), radius, keyword, category);
  });

  // 半径滑块事件
  const radiusRange = document.getElementById('radius-range');
  const radiusValue = document.getElementById('radius-value');
  radiusRange.addEventListener('input', function() {
    radiusValue.textContent = this.value + '米';
  });

  // 添加用户位置标记
  function addUserMarker(position) {
    new qq.maps.Marker({
      position: position,
      map: map,
      icon: new qq.maps.MarkerImage(
        'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/center.png',
        new qq.maps.Size(32, 32),
        new qq.maps.Point(16, 16)
      )
    });
  }

  // 搜索周边店铺
  function searchNearbyShops(lat, lng, radius = 1000, keyword = '店铺', category = '') {
    const params = new URLSearchParams({
      latitude: lat,
      longitude: lng,
      radius: radius,
      keyword: keyword,
      category: category
    });

    fetch(`/api/tencent-map/nearby-shops/?${params}`)
      .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
      })
      .then(data => {
        if (data.success) {
          displayShops(data.data);
          addShopMarkers(data.data);
        } else {
          console.error('搜索失败:', data.message);
        }
      })
      .catch(error => {
        console.error('API请求失败:', error);
        alert('获取附近店铺失败，请稍后重试');
      });
  }
  }

  // 在地图上添加店铺标记
  function addShopMarkers(shops) {
    // 清除旧标记
    if (window.shopMarkers) {
      window.shopMarkers.forEach(marker => marker.setMap(null));
    }
    
    window.shopMarkers = shops.map(shop => {
      const position = new qq.maps.LatLng(shop.location.lat, shop.location.lng);
      const marker = new qq.maps.Marker({
        position: position,
        map: map,
        title: shop.name
      });

      // 点击标记显示信息窗口
      qq.maps.event.addListener(marker, 'click', function() {
        const infoWindow = new qq.maps.InfoWindow({
          map: map,
          position: position,
          content: `<div class="info-window">
            <h3>${shop.name}</h3>
            <p>${shop.address}</p>
            <p>距离: ${shop.distance}米</p>
          </div>`
        });
      });

      return marker;
    });
  }

  // 显示店铺列表
  function displayShops(shops) {
    const shopListContainer = document.querySelector('.shop-list-container');
    
    fetch('/tencent-map/_shop_list/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken')
      },
      body: JSON.stringify({ shops: shops })
    })
    .then(response => response.text())
    .then(html => {
      shopListContainer.innerHTML = html;
      
      // 添加店铺点击事件
      document.querySelectorAll('.shop-item').forEach(item => {
        item.addEventListener('click', function() {
          const lat = parseFloat(this.dataset.lat);
          const lng = parseFloat(this.dataset.lng);
          map.panTo(new qq.maps.LatLng(lat, lng));
        });
      });
    });
  }

  // 获取CSRF token
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
});